<template>
  <div>
    <div>
      <el-row>
        <el-col :span="6">
          <el-input
            v-model="searchInput"
            placeholder="根据部门id查找部门"
            prefix-icon="el-icon-search"
            @input="watchsearch"
          ></el-input>
        </el-col>
<!--        <el-col :span="4">-->
<!--          <el-button @click="getEmployeeById">-->
<!--            搜索-->
<!--          </el-button>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-select v-model="rolevalue" placeholder="请选择查看类型" @change="getEmployeeByRole(rolevalue)">-->
<!--            <el-option-->
<!--              v-for="item in options"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-col>-->
        <el-col :span="4">
          <el-button @click="onInsertDepartment">新建部门</el-button>
        </el-col>
        <el-col :span="2">

          <el-button @click="exportExcel">导出部长表</el-button>
        </el-col>
        <el-col :span="4">
          <el-button @click="returnlogin">返回首页</el-button>
        </el-col>
      </el-row>
    </div>
  <div id="tables">
    <el-table
      :data="department"
      :row-style="{height: '0'}"
      :cell-style="{padding: '0'}"
      style="width: 100%"
      @row-click="getDetails"
      id="out-table"
    >
      <!--        <el-table-column label width="35">-->
      <!--          <template slot-scope="scope">-->
      <!--            <el-radio :label="scope.row.name" v-model="radioId">&nbsp;</el-radio>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <el-table-column align="center" prop="departmentId" label="部门Id" width="75"></el-table-column>
      <el-table-column align="center" prop="departmentName" label="部门名" width="60"></el-table-column>
      <el-table-column align="center" prop="userId" label="员工Id" width="100" fixed></el-table-column>
      <el-table-column align="center" prop="username" label="姓名" width="75"></el-table-column>
      <el-table-column align="center" prop="empNum" label="人数" width="75"></el-table-column>
      <el-table-column fixed="right" width="200" label="操作">
        <template slot-scope="scope">
          <el-button @click="opendialog(scope.row)" style="padding: 3px" size="mini">编辑部门信息</el-button>
<!--          <el-button @click="deleteEmp(scope.row)" style="padding: 3px" size="mini" type="primary">查看-->
<!--          </el-button>-->
       <el-button @click="deleteEmp(scope.row)" style="padding: 3px" size="mini" type="danger">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

    <el-dialog
      title="新 建 部 门"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="handleClose">
      <el-form ref="form" label-width="100px" v-model="departments" :rules="rule">
        <el-row>
          <el-col :span="6">
            <el-form-item label="部门id">
              <el-input v-model="departments.departmentId" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门名称">
              <el-input v-model="departments.departmentName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="未增员工Id" >
              <el-select v-model="usercache" placeholder="请选择员工" @change="getDepartmentFreeuserId(usercache)">
                <el-option
                  v-for="item in noDepartmenter"
                  :key="item.userId"
                  :label="item.userId"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工姓名" prop="name">
              <el-input v-model="departments.userName" disabled="true" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="工号">
              <el-input v-model="departments.workId" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门职位">
              <el-input v-model="departments.workName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitMessage">确 定 添 加</el-button>
  </span>
    </el-dialog>
    <el-dialog
      title="编辑部门信息"
      :visible.sync="modifyVisiable"
      width="80%"
      :before-close="handleClose">
      <el-form ref="form" label-width="100px" v-model="departments" :rules="rule">
        <el-row>
          <el-col :span="6">
            <el-form-item label="部门id">
              <el-input v-model="departments.departmentId"  disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门名称">
              <el-input v-model="departments.departmentName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item >
              <el-button @click="submitChange">修改部门名</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
    export default {
        name: "department_summary",

      data()
      {
        return{
          department:[],
          noDepartmenter:[],
          departments:{
            departmentId: "",
            departmentName: "",
            userId: "",
            userName: "",
            workId:"",
            workName:"",
            empNum:"",
          },
          dialogVisible:false,
          modifyVisiable:false,
          searchInput:"",
          usercache:"请选择雇员",
        }
      },
      mounted() {
        this.reloadDepartment()
        this.reloadnoDepartmenter()
      },
      methods:
        {


          //定义导出Excel表格事件
          exportExcel() {
            let xlsxParam = { raw: true }; //转换成excel时，使用原始的格式
            / generate workbook object from table /;
            /* 从表生成工作簿对象 */
            let table =  document.querySelector("#out-table").cloneNode(true)
            // 因为element-ui的表格的fixed属性导致多出一个table，会下载重复内容，这里删除掉
            table.removeChild(table.querySelector(".el-table__fixed-right"));
            table.removeChild(table.querySelector(".el-table__fixed"));
            let wb = XLSX.utils.table_to_book(
              table ,  //elementui 表格的id
              xlsxParam
            );

            /* 获取二进制字符串作为输出 */
            var wbout = XLSX.write(wb, {
              bookType: "xlsx",
              bookSST: true,
              type: "array"
            });
            try {
              FileSaver.saveAs(
                //Blob 对象表示一个不可变、原始数据的类文件对象。
                //Blob 表示的不一定是JavaScript原生格式的数据。
                //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
                //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
                new Blob([wbout], { type: "application/octet-stream" }),
                //设置导出文件名称
                "部长表.xlsx"
              );
            } catch (e) {
              if (typeof console !== "undefined") console.log(e, wbout);
            }
            return wbout;
          },


          reloadDepartment()
          {
            this.$axios.post("/department/getDepartment",{

            }).then((res)=>{
             // alert(JSON.stringify(res.data))

              this.department =[]
              this.department =res.data
            })
          },
          reloadnoDepartmenter()
          {
            this.usercache ="请选择雇员"
            this.departments.userId =""
            this.departments.userName = ""
            this.departments.departmentId = ""
            this.departments.departmentName = ""
            this.departments.workId = ""
            this.departments.workName = ""
            this.departments.empNum = 0

            this.noDepartmenter=[]
            this.usercache = ""
            this.$axios.post("/department/getUserIdByNoDepartment")
              .then((res)=>{
             //   alert(JSON.stringify(res.data))
                this.noDepartmenter = res.data
              })

          },
          opendialog(data)
          {
            this.departments.userId =""
            this.departments.userName = ""
            this.departments.departmentId = ""
            this.departments.departmentName = ""
            this.departments.workId = ""
            this.departments.workName = ""
            this.departments.empNum = 0
            alert(JSON.stringify(data))
            this.departments = data
            this.modifyVisiable = true
          },
          deleteEmp(data) {
            // alert("this.searchInput")
             alert(JSON.stringify(data.departmentId+":"+data.departmentName+":"+data.userId+":"+data.username))
            this.$confirm('此操作将清空【' +JSON.stringify(data.userId).replace(/\"/g, "")  + '】的部门及其成员为无部门状态, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {

                  this.$axios.post("/department/deleteDepartment",{
                            departmentId:data.departmentId,
                            departmentName:data.departmentName,
                            userId:data.userId,
                            userName:data.username
                  }).then((res)=>{
                      if(res.status == 200)
                      {
                        this.reloadDepartment()
                          return this.$message.success(res.data.msg)
                      }

                  }).catch((error)=>{
                    return this.$message.error("删除部门失败")
                  })



            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });
            });
          },



          watchsearch()
          {
            // alert(JSON.stringify(this.searchInput).replace(/\"/g, ""))
            if(this.searchInput ==''|| this.searchInput =='undefined'||this.searchInput == null)
            {
              this.reloadDepartment()
            }else{
              this.department = []
              this.$axios.post("/department/getDepartmentByDepartmentId",{
                departmentId:this.searchInput
              }).then((res)=>{
                this.department = res.data
              })
            }

          },
          getDepartmentFreeuserId(userIds)
          {

            this.uservalue = userIds

           this.$axios.post("/department/getUserNameByNoDepartment",{
                userId:userIds
           }).then((res)=>{
             //alert(JSON.stringify(res.data))
              this.departments.userName = res.data.username
           })

          },
          handleClose(done) {
            this.$confirm('确认关闭？')
              .then(_ => {
                this.dialogVisible = false
                this.modifyVisiable = false
                this.reloadnoDepartmenter()
                done();
              })
              .catch(_ => {


              });
          },
          submitMessage()
          {alert(JSON.stringify(this.usercache+this.departments.userName))
            this.$axios.post("/department/InsertnewDepartment",{
              departmentId:this.departments.departmentId,
              departmentName:this.departments.departmentName,
              userId:this.usercache,
              username:this.departments.userName
            }).then((res)=>{
                    if(res.status == 200)
                    {
                          this.$axios.post("/department/updatenewDepartmentEmpByuserId",{
                            departmentId:this.departments.departmentId,
                            departmentName:this.departments.departmentName,
                            userId:this.usercache,
                            workId:this.departments.workId,
                            workName:this.departments.workName
                          }).then((res1)=>{
                              if(res1.status == 200)
                              {
                                this.$axios.post("/employee/UpdateDepartmentByuserId",{
                                  departmentId:this.departments.departmentId,
                                  departmentName:this.departments.departmentName,
                                  userId:this.usercache,
                                  workId:this.departments.workId,
                                  workName:this.departments.workName
                                }).then((res2)=>{
                                    if(res2 .status == 200)
                                    {
                                      this.$axios.post("/department/updateRoleByuserId",{
                                        userId:this.usercache,
                                        role:"department"
                                      }).then((res3)=>{
                                        this.$axios.post("/department/UpdateDepartmentNum",{
                                          departmentId:this.departments.departmentId
                                        }).then((res4)=>{
                                          this.dialogVisible = false;
                                          this.reloadnoDepartmenter()
                                          this.reloadDepartment()
                                          return this.$message.success("创建部门成功！")
                                        })

                                      })



                                    }
                                    else {
                                      return this.$message.error("创建部门失败！")
                                    }
                                })

                              }else {
                                this.$axios.post("/department/deleteDepartmentByDepartmentId",{
                                  departmentId:this.departments.departmentId
                                }).then((res)=>{

                                })
                                return this.$message.error(res1.data.msg)
                              }
                          })
                    }
                    else {
                      return this.$message.error(res.data.msg)
                    }
            }).catch((error)=>{
              return this.$message.error("已有相同的部门Id")
            })
          },
          onInsertDepartment()
          {
            this.departments.userId =""
            this.departments.userName = ""
            this.departments.departmentId = ""
            this.departments.departmentName = ""
            this.departments.workId = ""
            this.departments.workName = ""
            this.departments.empNum = 0
            this.dialogVisible=true
          },
          submitChange()
          {
            alert(JSON.stringify(this.departments.departmentName))
            this.$axios.post("/department/updatedepartmentNameBydepartmentId",{
              departmentId:this.departments.departmentId,
              departmentName:this.departments.departmentName
            }).then((res)=>{
                    this.reloadnoDepartmenter()
                    this.reloadDepartment()
                    this.modifyVisiable = false
                  return this.$message.success("更新部门名成功")
            })
          },
          returnlogin(){
            this.$store.commit("setviewPage",1);
            this.$router.push({path: '/home'})
          },
        }
    }
</script>

<style scoped>

</style>
